package com.rzico.sbl.ui.report.manager

import android.widget.TextView
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.github.mikephil.extend.setChartValueSelectedListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportIncomeBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.model.ManagerGoodsData
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.ReportIncomeViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.showTimeRangeDialog

class ReportIncomeActivity : BaseActivity(R.layout.activity_report_income) {

    private val mBinding by lazy { ActivityReportIncomeBinding.bind(getRootView()) }

    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()

    // 商品收入
    private val mGoodsList = ArrayList<ManagerGoodsData>()
    private val mGoodsRange = ArrayList<ManagerDate>()
    private var mProductInSn = ""

    // 押桶
    private val mYaList = ArrayList<ManagerGoodsData>()
    private val mYaRange = ArrayList<ManagerDate>()
    private var mProductYaSn = ""

    // 买桶
    private val mBuyList = ArrayList<ManagerGoodsData>()
    private val mBuyRange = ArrayList<ManagerDate>()
    private var mProductBuySn = ""

    // 补差价
    private val mFillList = ArrayList<ManagerGoodsData>()
    private val mFillRange = ArrayList<ManagerDate>()
    private var mProductFillSn = ""

    override fun getViewModel() = get<ReportIncomeViewModel>()

    override fun initData() {
        initTitle(title = "收入", name = "近7天")

        initLayout()

        updateAllData()
    }

    private fun initLayout() {
        mBinding.also {
            it.incomeIn1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    xTextSize = 8f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mGoodsList.indices) ""
                    else mGoodsList[value.toInt()].name
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductInSn = mGoodsList[index].sn
                        mBinding.incomeInTitle.text = mGoodsList[index].name
                        getGoodsRangeData()
                    }
                }
            }

            it.incomeIn2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mGoodsRange.indices) ""
                    else mGoodsRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.incomeYa1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mYaList.indices) ""
                    else mYaList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductYaSn = mYaList[index].name
                        mBinding.incomeYaTitle.text = mYaList[index].name
                        getBucketRangeData("pledge")
                    }
                }
            }

            it.incomeYa2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mYaRange.indices) ""
                    else mYaRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.incomeMai1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mBuyList.indices) ""
                    else mBuyList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductBuySn = mBuyList[index].name
                        mBinding.incomeMaiTitle.text = mBuyList[index].name
                        getBucketRangeData("buy")
                    }
                }
            }

            it.incomeMai2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mBuyRange.indices) ""
                    else mBuyRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.incomeBu1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mFillList.indices) ""
                    else mFillList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mProductFillSn = mFillList[index].name
                        mBinding.incomeBuTitle.text = mFillList[index].name
                        getBucketRangeData("differPrice")
                    }
                }
            }

            it.incomeBu2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mFillRange.indices) ""
                    else mFillRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }

        tvRight?.oneClick { text ->
            text as TextView

            getViewModel()
                .showDropTimeFilter(
                    context = getIContext(),
                    bottom = text,
                    list = getViewModel().mTimeCheckList
                ) { bean ->

                    (bean.id != "4")
                        .condition {
                            getViewModel().mTimeCheckList.last().name = "自定义时间"
                        }

                    when (bean.id) {
                        "1" -> {
                            mBeginDate = getBeforeDate(6)
                            mEndDate = getTodayDate()
                            text.text = "近7天"

                            updateAllData()
                        }
                        "2" -> {
                            mBeginDate = getFirstDate()
                            mEndDate = getEndDate()
                            text.text = "本月"

                            updateAllData()
                        }
                        "3" -> {
                            mBeginDate = getBeforeFirstDate()
                            mEndDate = getBeforeEndDate()
                            text.text = "上月"

                            updateAllData()
                        }
                        "4" -> {
                            showTimeRangeDialog(
                                minYearValue = 2021,
                                isCurrentDate = true,
                                isAfterLimited = true,
                                onResult = { start, end ->
                                    getViewModel()
                                        .mTimeCheckList
                                        .forEach { it.isChecked = false }

                                    getViewModel()
                                        .mTimeCheckList
                                        .last()
                                        .isChecked = true

                                    mBeginDate = start
                                    mEndDate = end
                                    text.text = "自定义时间"
                                    bean.name = "$mBeginDate ~ $mEndDate"

                                    updateAllData()
                                }
                            )
                        }
                    }
                }
        }
    }

    /**
     * 设置所有商品销量
     */
    private fun setGoodsChart() {
        mBinding
            .incomeIn1
            .apply {
                if (mGoodsList.none { it.amount.doubleValue > 0 }) {
                    clear()
                    mBinding.incomeIn2.clear()
                    mBinding.incomeInTitle.text = "暂无商品"
                } else {
                    setSingleData(
                        entries = mGoodsList.mapIndexed { index, data ->
                            BarEntry(index.toFloat(), data.amount.toFloat())
                        },
                        colorList = getViewModel().brandColor(),
                        formatter = CustomValueFormatter()
                    )
                }

                animateY(500)
            }
    }

    /**
     * 设置单个商品最近销量
     */
    private fun setGoodsRangeChart() {
        mBinding.incomeIn2.apply {
            setSingleData(
                entries = mGoodsRange.mapIndexed { index, data ->
                    BarEntry(index.toFloat(), data.amount.toFloat())
                },
                colorList = listOf(
                    getViewModel()
                        .brandColor()[
                            mGoodsList.indexOfFirst { it.sn == mProductInSn } % 24
                        ]
                ),
                isHighlight = false,
                formatter = CustomValueFormatter()
            )

            animateY(500)
        }
    }

    /**
     * 设置所有品牌销量
     */
    private fun setBucketChart(type: String) {
        mBinding.also { layout ->
            when (type) {
                "pledge" -> {
                    layout
                        .incomeYa1
                        .apply {
                            if (mYaList.isEmpty()) {
                                clear()
                                mBinding.incomeYa2.clear()
                                mBinding.incomeYaTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mYaList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                            animateY(500)
                        }
                }
                "buy" -> {
                    layout
                        .incomeMai1
                        .apply {
                            if (mBuyList.isEmpty()) {
                                clear()
                                mBinding.incomeMai2.clear()
                                mBinding.incomeMaiTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mBuyList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                            animateY(500)
                        }
                }
                "differPrice" -> {
                    layout
                        .incomeBu1
                        .apply {
                            if (mFillList.isEmpty()) {
                                clear()
                                mBinding.incomeBu2.clear()
                                mBinding.incomeBuTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mFillList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                            animateY(500)
                        }
                }
            }
        }
    }

    /**
     * 设置单个品牌最近销量
     */
    private fun setBucketRangeChart(type: String) {
        when (type) {
            "pledge" -> {
                mBinding
                    .incomeYa2
                    .apply {
                        setSingleData(
                            entries = mYaRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mYaList.indexOfFirst { it.name == mProductYaSn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
            "buy" -> {
                mBinding
                    .incomeMai2
                    .apply {
                        setSingleData(
                            entries = mBuyRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mBuyList.indexOfFirst { it.name == mProductBuySn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
            "differPrice" -> {
                mBinding
                    .incomeBu2
                    .apply {
                        setSingleData(
                            entries = mFillRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mFillList.indexOfFirst { it.name == mProductFillSn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
        }
    }

    /**
     * 获取所有商品销量
     */
    private fun getGoodsListData() {
        getViewModel()
            .goodsList(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    mGoodsList.clear()
                    mGoodsList.addItems(list)

                    setGoodsChart()

                    if (mGoodsList.isNotEmpty()) {
                        if (mGoodsList.none { it.sn == mProductInSn }) {
                            mProductInSn = mGoodsList[0].sn
                            mBinding.incomeInTitle.text = mGoodsList[0].name
                        }
                        getGoodsRangeData()
                    }
                }
            )
    }

    /**
     * 获取单个商品最近销量
     */
    private fun getGoodsRangeData() {
        getViewModel()
            .goodsRangeList(
                goodsSn = mProductInSn,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mGoodsRange.clear()
                    mGoodsRange.addItems(it)

                    setGoodsRangeChart()
                }
            )
    }

    /**
     * 获取所有品牌销量
     */
    private fun getBucketListData(type: String) {
        getViewModel()
            .bucketList(
                type = type,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    when (type) {
                        "pledge" -> {
                            mYaList.clear()
                            mYaList.addItems(list)

                            if (mYaList.isNotEmpty()) {
                                if (mYaList.none { it.name == mProductYaSn }) {
                                    mProductYaSn = mYaList[0].name
                                    mBinding.incomeYaTitle.text = mYaList[0].name
                                }
                                getBucketRangeData(type)
                            }
                        }
                        "buy" -> {
                            mBuyList.clear()
                            mBuyList.addItems(list)

                            if (mBuyList.isNotEmpty()) {
                                if (mBuyList.none { it.name == mProductBuySn }) {
                                    mProductBuySn = mBuyList[0].name
                                    mBinding.incomeMaiTitle.text = mBuyList[0].name
                                }
                                getBucketRangeData(type)
                            }
                        }
                        "differPrice" -> {
                            mFillList.clear()
                            mFillList.addItems(list)

                            if (mFillList.isNotEmpty()) {
                                if (mFillList.none { it.name == mProductFillSn }) {
                                    mProductFillSn = mFillList[0].name
                                    mBinding.incomeBuTitle.text = mFillList[0].name
                                }
                                getBucketRangeData(type)
                            }
                        }
                    }

                    setBucketChart(type)
                }
            )
    }

    /**
     * 获取单个品牌最近销量
     */
    private fun getBucketRangeData(type: String) {
        getViewModel()
            .bucketRangeList(
                type = type,
                barrel = when (type) {
                    "pledge" -> mProductYaSn
                    "buy" -> mProductBuySn
                    "differPrice" -> mProductFillSn
                    else -> ""
                },
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    when (type) {
                        "pledge" -> {
                            mYaRange.clear()
                            mYaRange.addItems(it)
                        }
                        "buy" -> {
                            mBuyRange.clear()
                            mBuyRange.addItems(it)
                        }
                        "differPrice" -> {
                            mFillRange.clear()
                            mFillRange.addItems(it)
                        }
                    }

                    setBucketRangeChart(type)
                }
            )
    }

    /**
     * 刷新所有数据
     */
    private fun updateAllData() {
        getGoodsListData()
        getBucketListData("pledge")
        getBucketListData("buy")
        getBucketListData("differPrice")
    }

}